package com.gxar.marketdelivery.application.command;

import com.gxar.marketdelivery.application.context.DeliveryContext;
import com.gxar.marketdelivery.domain.factory.MaterialFactory;
import com.gxar.marketdelivery.interfaces.web.result.CDeliveryPlanResult;
import com.gxar.marketdelivery.shared.model.DeliveryPlanModel;
import com.gxar.marketdelivery.shared.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author nice
 * @version 1.0
 * @created 2023/8/2.
 */
@Service
@Slf4j
public class DeliveryBuilder {
    @Autowired
    protected MaterialFactory materialFactory;

    public List<CDeliveryPlanResult> buildPlan(DeliveryContext context, List<DeliveryPlanModel> planModels) {
        /**
         * 1.通过AB过滤物料
         * 2.物料动态解析
         * 3.url解析
         * 4.组装
         */
        if (CollectionUtils.isEmpty(planModels)) {
            return Collections.emptyList();
        }
        Map<Long, String> planMaterialAndAbtestMap = materialFactory.parseMaterial(context, planModels);
        return planModels.stream().filter(model -> planMaterialAndAbtestMap.containsKey(model.getId()))
                .map((planModel) -> {
                    String materialJson = planMaterialAndAbtestMap.get(planModel.getId());
                    CDeliveryPlanResult planInfo = new CDeliveryPlanResult();
                    Long planId = planModel.getId();
                    planInfo.setId(String.valueOf(planId));
                    planInfo.setResSlotId(String.valueOf(planModel.getResSlotId()));
                    planInfo.setUrl(Strings.EMPTY);
                    planInfo.setMaterialJson(materialJson);
                    planInfo.setPlanTraceId(DeliveryTraceIdGenerator.genPlanTraceId(planId, planModel.getResSlotId()));
                    return planInfo;
                }).collect(Collectors.toList());
    }
}
